const circles = [
  { color: "purple", top: "55", left: "10" },
  { color: "blue", top: "10", left: "45" },
  { color: "orange", top: "30", left: "75" },
];
function createBgPanel() {
  const newElement = document.createElement("div");
  newElement.id = "bg-container";
  document.body.appendChild(newElement);
  return newElement;
}
function createBgCircle(colorName, top, left) {
  const newElement = document.createElement("div");
  newElement.className = "circle " + colorName;
  newElement.style.position = "absolute";
  newElement.style.top = top + "%";
  newElement.style.left = left + "%";

  let bgContainerElement = document.getElementById("bg-container");
  if (bgContainerElement == null || bgContainerElement == undefined) {
    bgContainerElement = createBgPanel();
  }

  bgContainerElement.appendChild(newElement);
}
createBgPanel();
circles.forEach((circleItem) =>
  createBgCircle(circleItem.color, circleItem.top, circleItem.left)
);

function moveCircle(circleElement) {
  if (circleElement == null || circleElement == undefined) return;
  const durationTime = 3000;
  const distance = 400;
  let startTime = null;
  let direction = 1;

  function animate(time) {
    if (!startTime) startTime = time;
    const elapsed = time - startTime;
    const progress = (elapsed / durationTime) % 1;
    const currentPosition =
      direction > 0 ? progress * distance : distance - progress * distance;
    circleElement.style.transform = `translateX(${currentPosition}px)`;

    if (elapsed < durationTime) {
      requestAnimationFrame(animate);
    } else {
      direction *= -1;
      startTime = null;
      requestAnimationFrame(animate);
    }
  }
  requestAnimationFrame(animate);
}

function startMoveCircle() {
  const circleElements = document.querySelectorAll(".circle");
  if (circleElements == null || circleElements == undefined) return;
  circleElements.forEach((circleItem) => moveCircle(circleItem));
}
startMoveCircle();
